package com.photographysharing.util;

import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Map;

@Component
public class RedisHelp {
    private  JedisPool pool;
    private  Jedis jedis;
    public RedisHelp(){
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(10); // 设置最大连接数
        poolConfig.setMaxIdle(5); // 设置最大空闲连接数
        pool =new JedisPool(poolConfig,"localhost", 6379);
    }

    public  boolean setString(String key,String value,int minutes){
        try(Jedis jedis = pool.getResource()){
            jedis.set(key,value);
            jedis.expire(key,minutes*60);
            return true;
        }catch (Exception e){
            return false;
        }

    }
    public  boolean setString(String key,String value){
        try(Jedis jedis = pool.getResource()){
            jedis.set(key,value);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    public  String getString(String key){
        try(Jedis jedis = pool.getResource()){
            return key==null?null:jedis.get(key);
        }
    }
    public boolean removeKey(String key){
        try(Jedis jedis = pool.getResource()){
            jedis.del(key);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    public boolean setObject(String key,Object object){
        try(Jedis jedis = pool.getResource()){
            String json = StringUtil.mapToString(object);
            jedis.set(key,json);
            return true;
        }catch (Exception e){
            return false;
        }

    }

    public Map<String,Object> getObject(String key){
        try(Jedis jedis = pool.getResource()){
            String json = jedis.get(key);
            return json==null?null:StringUtil.stringToMap(json);
        }

    }



}
